package org.raymond.iworks.study.spring.service;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.raymond.iworks.study.spring.repository.LockSQLRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * @author raymond
 * @version V1.0
 * @Description: TODO
 */
@Slf4j
@Service
public class LockSQLService {
    @Autowired
    private LockSQLRepository lockSQLRepository;

    //@Transactional
    public void queryRepeatableRead(){
        // 通过非唯一索引字段查询
        Map<String, Object> map = lockSQLRepository.queryNonUIdxField(6);
        log.info("1 count:{}", JSONUtil.toJsonStr(map));
        try {
            Thread.sleep(1000*6);
        } catch (InterruptedException e) {
        }
        map = lockSQLRepository.queryNonUIdxField(6);
        log.info("2 count:{}", JSONUtil.toJsonStr(map));
        map = lockSQLRepository.queryNonUIdxField(5);
        log.info("3 count:{}", JSONUtil.toJsonStr(map));
    }

    @Transactional(isolation = Isolation.REPEATABLE_READ)
    public void updateGap(){
        // 一个修改记录的事务
        int r = lockSQLRepository.updateGap();
        Map<String, Object> map = lockSQLRepository.queryNonUIdxField(5);
        log.info("updated:{}, {}", r, JSONUtil.toJsonStr(map));
    }

    //@Transactional(isolation = Isolation.READ_COMMITTED)
    public void queryPhantomRead(){
        int i = lockSQLRepository.countGap();
        log.info("1 count:{}", i);
        try {
            Thread.sleep(1000*6);
        } catch (InterruptedException e) {
        }
        i = lockSQLRepository.countGap();
        log.info("2 count:{}", i);
        i = lockSQLRepository.countGap();
        log.info("3 count:{}", i);
    }

    @Transactional(isolation = Isolation.READ_COMMITTED)
    public void insertGap(){
        // 一个插入记录的事务
        int r = lockSQLRepository.insertGap();
        int i = lockSQLRepository.countGap();
        log.info("insert: {}, {}", r, i);
    }

    @Transactional
    public void reset(){
        lockSQLRepository.remove();
        lockSQLRepository.insert1();
        lockSQLRepository.insert2();
        lockSQLRepository.insert3();
    }
}
